// eslint-disable-next-line no-unused-vars
import axios from "axios";
import VueCookies from 'vue-cookies'

const BASE_URL = process.env.VUE_APP_BASE_URL


const addTokenHeader = (config) => {
    config = config ? config : {}
    let tokenHeader = {};
    VueCookies.get('utoken') && (tokenHeader["X-TOKEN-UTOKEN"] = VueCookies.get('utoken'));
    VueCookies.get('gtoken') && (tokenHeader["X-TOKEN-GTOKEN"] = VueCookies.get('gtoken'));
    config.headers = Object.assign(tokenHeader, config.headers)
    return config;

}

const convertParams = (params) => {
    let paramsStr = "?";
    params = params ? params : {};
    for (let key in params) {
        let value = params[key]
        if (!(key || value)) continue;
        paramsStr = paramsStr === "?" ? paramsStr : paramsStr + "&";
        paramsStr = paramsStr + key + "=" + value;
    }
    return paramsStr === "?" ? "" : paramsStr
}

export const createGet = (path) => {
    let httpGet = axios.create({maxRedirects: 16, method: "GET"});
    return (params, config) => {
        let paramsStr = convertParams(params);
        let realUrl = BASE_URL + path;
        return httpGet.get(realUrl + paramsStr, addTokenHeader(config))
    }
}

export const createPost = (path) => {
    let httpPost = axios.create({maxRedirects: 16, method: "POST"});
    return (body, params = null, config) => {
        let paramsStr = convertParams(params);
        let realUrl = BASE_URL + path;
        return httpPost.post(realUrl + paramsStr, body, addTokenHeader(config))
    }
}
